<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<TITLE>Chapter 2</TITLE>
<META name="Robots" content="NONE">
<link rel="stylesheet" href="./style.css">
</HEAD>
<BODY>
<H2>CHAPTER 2: Pointer types and Arrays </H2>
<P>
Okay, let's move on. Let us consider why we need to identify the
<I><B>type</B></I> of variable that a pointer points to, as in:
<PRE><CODE>
     int *ptr;
</CODE></PRE>
<P>
One reason for doing this is so that later, once ptr &quot;points
to&quot; something, if we write:
<PRE><CODE>
    *ptr = 2;
</CODE></PRE>
<P>
the compiler will know how many bytes to copy into that memory
location pointed to by <B>ptr</B>. If <B>ptr</B> was declared
as pointing to an integer, 4 bytes would be
copied.<strike>&nbsp;</strike> Similarly for floats and doubles the
appropriate number will be copied. But, defining the type that
the pointer points to permits a number of other interesting ways
a compiler can interpret code. For example, consider a block in
memory consisting if ten integers in a row. That is, 40
bytes
of memory are set aside to hold 10 integers.
<P>
Now, let's say we point our integer pointer <B>ptr</B> at the
first of these integers. Furthermore lets say that integer is
located at memory location 100 (decimal). What happens when we
write:
<PRE><CODE>
    ptr + 1;

</CODE></PRE>
<P>
Because the compiler &quot;knows&quot; this is a pointer (i.e.
its value is an address) and that it points to an integer (its
current address, 100, is the address of an integer), it adds 4 to <B>ptr</B> instead of 1, so the pointer &quot;points to&quot;
the <B>next</B> <B>integer</B>, at memory location 104. Similarly,
were the <B>ptr</B> declared as a pointer to a short, it would
add 2 to it instead of 1. The same goes for other data types such
as floats, doubles, or even user defined data types such as structures.
This is obviously not the same kind of &quot;addition&quot; that
we normally think of. In C it is referred to as addition using
&quot;pointer arithmetic&quot;, a term which we will come back
to later.<P>
Similarly, since <B>++ptr</B> and <B>ptr++</B> are both equivalent
to <B>ptr + 1</B> (though the point in the program when <B>ptr</B>
is incremented may be different), incrementing a pointer using
the unary ++ operator, either pre- or post-, increments the address
it stores by the amount sizeof(type) where &quot;type&quot; is
the type of the object pointed to. (i.e. 4 for an integer).
<P>
Since a block of 10 integers located contiguously in memory is,
by definition, an array of integers, this brings up an interesting
relationship between arrays and pointers.
<P>
Consider the following:
<PRE><CODE>
    int my_array[] = {1,23,17,4,-5,100};
</CODE></PRE>
<P>
Here we have an array containing 6 integers. We refer to each
of these integers by means of a subscript to <B>my_array</B>,
i.e. using <B>my_array[0]</B> through <B>my_array[5]</B>. But,
we could alternatively access them via a pointer as follows:
<PRE><CODE>
    int *ptr;
    ptr = &amp;my_array[0];       /* point our pointer at the first
                                 integer in our array */
</CODE></PRE>
<P>
And then we could print out our array either using the array notation
or by dereferencing our pointer. The following code illustrates
this:
<PRE><CODE>
-----------  Program 2.1  -----------------------------------

/* Program 2.1 from PTRTUT10.HTM   6/13/97 */

#include &lt;stdio.h&gt;

int my_array[] = {1,23,17,4,-5,100};
int *ptr;

int main(void)
{
    int i;
    ptr = &amp;my_array[0];     /* point our pointer to the first
                                      element of the array */
    printf(&quot;\n\n&quot;);
    for (i = 0; i &lt; 6; i++)
    {
      printf(&quot;my_array[%d] = %d   &quot;,i,my_array[i]);   /*&lt;-- A */
      printf(&quot;ptr + %d = %d\n&quot;,i, *(ptr + i));        /*&lt;-- B */
    }
    return 0;
}
</CODE></PRE>
<P>
Compile and run the above program and carefully note lines A and
B and that the program prints out the same values in either case.
Also observe how we dereferenced our pointer in line B, i.e. we
first added i to it and then dereferenced the new pointer. Change
line B to read:
<PRE><CODE>
    printf(&quot;ptr + %d = %d\n&quot;,i, *ptr++);
</CODE></PRE>
<P>
and run it again... then change it to:
<PRE><CODE>
    printf(&quot;ptr + %d = %d\n&quot;,i, *(++ptr));
</CODE></PRE>
<P>
and try once more. Each time try and predict the outcome and carefully
look at the actual outcome.
<P>
In C, the standard states that wherever we might use <B>&amp;var_name[0]</B>
we can replace that with <B>var_name</B>, thus in our code where
we wrote:
<PRE><CODE>
    ptr = &amp;my_array[0];
</CODE></PRE>
<P>
we can write:
<PRE><CODE>
    ptr = my_array;
</CODE></PRE>
<P>
to achieve the same result.
<P>
This leads many texts to state that the name of an array is a
pointer. I prefer to mentally think &quot;the name of the array
is the address of first element in the array&quot;. Many beginners
(including myself when I was learning) have a tendency to become
confused by thinking of it as a pointer. For example, while we
can write
<PRE><CODE>
    ptr = my_array;
</CODE></PRE>
<P>
we cannot write
<PRE><CODE>
    my_array = ptr;
</CODE></PRE>
<P>
The reason is that while <B>ptr</B> is a variable, <B>my_array</B>
is a constant. That is, the location at which the first element
of <B>my_array</B> will be stored cannot be changed once <B>my_array[]</B>
has been declared.
<P>
Earlier when discussing the term &quot;lvalue&quot; I cited K&amp;R-2
where it stated:
<BLOCKQUOTE>
&quot;An <B>object</B> is a named region of storage; an <B>lvalue</B>
is an expression referring to an object&quot;.
</BLOCKQUOTE>
<P>
This raises an interesting problem. Since <B>my_array</B> is a
named region of storage, why is <B>my_array</B> in the above assignment
statement not an lvalue? To resolve this problem, some refer to
<B>my_array</B> as an &quot;unmodifiable lvalue&quot;.
<P>
Modify the example program above by changing
<PRE><CODE>
    ptr = &amp;my_array[0];
</CODE></PRE>
<P>
to
<PRE><CODE>
    ptr = my_array;
</CODE></PRE>
<P>
and run it again to verify the results are identical.
<P>
Now, let's delve a little further into the difference between
the names <B>ptr</B> and <B>my_array</B> as used above. Some writers
will refer to an array's name as a <I><B>constant</B></I> pointer.
What do we mean by that? Well, to understand the term &quot;constant&quot;
in this sense, let's go back to our definition of the term &quot;variable&quot;.
When we declare a variable we set aside a spot in memory to hold
the value of the appropriate type. Once that is done the name
of the variable can be interpreted in one of two ways. When used
on the left side of the assignment operator, the compiler interprets
it as the memory location to which to move that value resulting
from evaluation of the right side of the assignment operator.
But, when used on the right side of the assignment operator, the
name of a variable is interpreted to mean the contents stored
at that memory address set aside to hold the value of that variable.
<P>
With that in mind, let's now consider the simplest of constants,
as in:
<PRE><CODE>
    int i, k;
    i = 2;
</CODE></PRE>
<P>
Here, while <B>i</B> is a variable and then occupies space in
the data portion of memory, <B>2</B> is a constant and, as such,
instead of setting aside memory in the data segment, it is imbedded
directly in the code segment of memory. That is, while writing
something like <B>k = i;</B> tells the compiler to create code
which at run time will look at memory location <B>&amp;i</B> to
determine the value to be moved to <B>k</B>, code created by <B>i
= 2;</B> simply puts the <B>2</B> in the code and there is no
referencing of the data segment. That is, both <B>k</B> and <B>i</B>
are objects, but <B>2</B> is not an object.
<P>
Similarly, in the above, since <B>my_array</B> is a constant,
once the compiler establishes where the array itself is to be
stored, it &quot;knows&quot; the address of <B>my_array[0]</B>
and on seeing:
<PRE><CODE>
    ptr = my_array;
</CODE></PRE>
<P>
it simply uses this address as a constant in the code segment
and there is no referencing of the data segment beyond that.
<P>
This might be a good place explain further the use of the<B> (void
*) </B>expression used in Program 1.1 of Chapter 1. As we have
seen we can have pointers of various types. So far we have discussed
pointers to integers and pointers to characters. In coming chapters
we will be learning about pointers to structures and even pointer
to pointers.
<P>
Also we have learned that on different systems the size of a pointer
can vary. As it turns out it is also possible that the size of
a pointer can vary depending on the data type of the object to
which it points. Thus, as with integers where you can run into
trouble attempting to assign a long integer to a variable of type
short integer, you can run into trouble attempting to assign the
values of pointers of various types to pointer variables of other
types.
<P>
To minimize this problem, C provides for a pointer of type void.
We can declare such a pointer by writing:
<PRE><CODE>
void *vptr;
</CODE></PRE>
<P>
A void pointer is sort of a generic pointer. For example, while
C will not permit the comparison of a pointer to type integer
with a pointer to type character, for example, either of these
can be compared to a void pointer. Of course, as with other variables,
casts can be used to convert from one type of pointer to another
under the proper circumstances. In Program 1.1. of Chapter 1 I
cast the pointers to integers into void pointers to make them
compatible with the %p conversion specification. In later chapters
other casts will be made for reasons defined therein.
<P>
Well, that's a lot of technical stuff to digest and I don't expect
a beginner to understand all of it on first reading. With time
and experimentation you will want to come back and re-read the
first 2 chapters. But for now, let's move on to the relationship
between pointers, character arrays, and strings.
<DL>
<DT><CENTER><A HREF=ch3x.htm>Chapter 3: Pointers and Strings</A></P></CENTER>
<DT><CENTER><A Href=pointers.htm>Back to Table of Contents</A></CENTER>
<DT>
<DD>
</DL>
</BODY>
</HTML>
